<?php

namespace haibao\jiepai\data;
use \haibao\jiepai\common\App as AppCommon;

class Booth extends \haibao\jiepai\data\BaseMysql{

    public function __construct(){
        parent::__construct('\haibao\jiepai\model\data\article\CmsArticles');
    }
    
    public function delPopularTag($tagId, $type){

        $sql = "INSERT INTO cms_blocklist (`Type`,TypeID) values(%s,%s)";
        $this->query($sql, array($type, $tagId));

    }

    public function recoverPopularTag($tagId, $type){

        $sql = "delete from cms_blocklist where `Type`=%s and TypeID=%s";
        $this->query($sql, array((int)$type, (int)$tagId));

    }

    /**
     * 处理头条焦点
     */
    public function updateFocusStatus(){

        $sql = "Update cms_focus_material SET Status = %s WHERE  Status = %s AND Flag = 0 AND UpTime <= %s";
        $this->query($sql,array(\haibao\jiepai\model\data\booth\CmsFocusMaterial::STATUS_HAS_USE, \haibao\jiepai\model\data\booth\CmsFocusMaterial::STATUS_NOT_USE, date('Y-m-d H:i:s')));
    }
    /* 获取焦点图列表 */
    public function getFocusList(){
        $sql = "SELECT t1.*,t3.NickName as EditorName from cms_focus_material t1" .
            " LEFT JOIN cms_users t3 on t3.UserID = t1.Editor " .
            " where (t1.UpTime <= %s AND (t1.DownTime > %s OR t1.DownTime = '0000-00-00 00:00:00')) AND t1.Category=%s ORDER BY t1.UpIndex,t1.ID desc,t1.CreateTime desc;";
        $result = $this->query($sql,array(date('Y-m-d H:i:s'),date('Y-m-d H:i:s'),\haibao\jiepai\model\data\booth\CmsFocusMaterial::CATEGORY_FOUCS));

        $list = array();
        while($row = $result->fetch_assoc()){
            array_push($list, $row);
        }
        return $list;
    }
    /* 获取头条置顶位列表 */
    public function getHeadFocusList($option){

        $sql = "SELECT t1.*,t3.NickName as EditorName from cms_focus_material t1" .
                " LEFT JOIN cms_users t3 on t3.UserID = t1.Editor " .
                " where (t1.UpTime < %s AND (t1.DownTime > %s OR t1.DownTime = '0000-00-00 00:00:00')) AND t1.Category=%s AND t1.Flag=0 ";
        if($option && isset($option['ID']) && $option['ID']>0){
            $sql .= " AND t1.ID != ".$option['ID'];
        }
        $sql .= " ORDER BY t1.UpIndex,t1.UpTime desc LIMIT 3;";
        $result = $this->query($sql,array(date('Y-m-d H:i:s'),date('Y-m-d H:i:s'),\haibao\jiepai\model\data\booth\CmsFocusMaterial::CATEGORY_HEAD_ARTICLE));
        $list = array();
        while($row = $result->fetch_assoc()){
            array_push($list, $row);
        }
        return $list;
    }
    /* 获取头条信息流位列表 */
    public function GetHomeFocusList(){

        $sql = "SELECT t1.*,t3.NickName as EditorName from cms_focus_material t1" .
            " LEFT JOIN cms_users t3 on t3.UserID = t1.Editor " .
            " where (t1.UpTime < %s AND (t1.DownTime > %s OR t1.DownTime = '0000-00-00 00:00:00')) AND t1.Category=%s AND t1.Flag=0  AND t1.UpIndex in (2,6) GROUP BY t1.UpIndex ORDER BY t1.UpIndex,t1.ID desc,t1.CreateTime desc LIMIT 2;";
        $result = $this->query($sql,array(date('Y-m-d H:i:s'),date('Y-m-d H:i:s'),\haibao\jiepai\model\data\booth\CmsFocusMaterial::CATEGORY_HEAD_MESSAGE_STREAM));
        $list = array();
        while($row = $result->fetch_assoc()){
            array_push($list, $row);
        }
        return $list;
    }

    public function getSpecialColumnInfo($columnId){

        $sql = 'SELECT c.ColumnName,c.Description,c.TagID,c.ColumnType,c.UpdateDate,c.PictureID,c.Status as CanSubscribe  FROM cms_columns c WHERE ColumnType=3 AND TagID=%s';

        $result = $this->query($sql, array($columnId))->fetch_assoc();
        if($result){
            $pictureInfo = \haibao\cms\business\ImageLibrary::getImageById($result['PictureID']);
            $result['Picture'] = $result['Width'] = $result['Height'] = '';
            if($pictureInfo){
                $result['Picture'] = $pictureInfo->Filename;
                $result['Width'] = $pictureInfo->Width;
                $result['Height'] = $pictureInfo->Height;
            }
        }
        return $result;
    }

    public function getSpecialColumnArticles($columnId, $cursor, $isEditor=0){

        //$sql = "SELECT ca.PublishTime,ca.Subtitle as KeyWord,ca.ArticleID,ca.Type,ca.Title,cf.Ratio,cf.ServerFileName as Picture,cf.FileWidth,cf.FileHeight,cf.CropX,cf.CropY,cf.CropWidth,cf.CropHeight " +
        $sql = "SELECT ca.ArticleID,ca.PublishTime,ca.Subtitle as KeyWord,ca.Type,ca.Title,cac.ContentInfo " .
            " from cms_articles ca " .
            "left join cms_article_content cac on ca.ArticleID=cac.ArticleID " .
            "WHERE ca.PublishStatus=1 AND ca.Type=%s AND cac.Type=6 AND ca.Flag=0 AND cac.Flag=0 ";
        if($cursor){
            $sql .= " AND ca.PublishTime < '".date('Y-m-d H:i:s',$cursor)."' ";
        }

        if(!$isEditor){
            $sql .= " AND ca.PublishTime < Now() ";
        }
        
        $sql .= " ORDER BY ca.PublishTime desc LIMIT ".\haibao\classlibrary\jiepai\Config::getConfig(\haibao\classlibrary\jiepai\Config::LARGE_ARTICLE_PAGE_SIZE);
        $result = $this->query($sql, array($columnId));
        $articleList = array();
        $tmpImageIds = array();
        while($row = $result->fetch_assoc()){
            array_push($articleList, $row);
        }

        if($articleList){

            $articleList = self::mergeDataAndImage($articleList);

        }
        return $articleList;
    }

    public function getWeeklyPersonInfo($articleIds){
        $str = preg_replace('/\d+/', '%s', implode(',', $articleIds));
        $sql = 'select ArticleID,CelebrityID from cms_article_celebrity where ArticleID in('.$str.')';
        $result = $this->query($sql, $articleIds);
        $list = array();
        while ($row = $result->fetch_assoc()){
            $list[$row['ArticleID']] = $row['CelebrityID'];
        }
        return $list;
    }

    public function getTopicById($topicId){
        $sql = 'SELECT t.TopicID,t.Introduction,t.Title,t.TopicTitlePictureID FROM cms_topics t WHERE t.TopicID=%s';
        $topicInfo = $this->query($sql, array($topicId))->fetch_assoc();

        if($topicInfo){
            $topicInfo = self::mergeOneDataAndImage($topicInfo,(int)$topicInfo['TopicTitlePictureID']);
        }
        return $topicInfo;
    }

    public function getTopicKeyRecArticles($topicId){
        $sql = 'SELECT t.ArticleID,a.Title,a.Type,a.PictureNum,c.ContentInfo FROM cms_topics_key_rec t  ' .
            'LEFT JOIN cms_articles a ON t.ArticleID=a.ArticleID ' .
            'LEFT JOIN cms_article_content c ON t.ArticleID=c.ArticleID AND c.Type=0 ' .
            'WHERE t.TopicID=%s';
        $result = $this->query($sql, array($topicId));

        $articleList = array();
        while($row = $result->fetch_assoc()){
            array_push($articleList, $row);
        }

        return self::mergeDataAndImage($articleList);
    }

    public function getHotRecommendBanners($version){
        $sql = "SELECT t1.Type,t1.TypeID,t1.Picture,t1.Title,t1.Link from cms_focus_material t1" .
            " where  t1.Category = 1 AND t1.Flag = 0 AND (t1.UpTime < NOW() AND (t1.DownTime > NOW() OR t1.DownTime = '0000-00-00 00:00:00')) ";

        /*if(!AppCommon::compareAppVersion(\haibao\classlibrary\jiepai\Config::getConfig(\haibao\classlibrary\jiepai\Config::LAST_SUPPORT_VERSION_430), $version)){
            $sql .= " AND t1.Type!= 108 AND (SELECT count(*) as count from cms_article_content WHERE ArticleID=t1.TypeID AND Type=14) = 0 ";
        }else if(!AppCommon::compareAppVersion(\haibao\classlibrary\jiepai\Config::getConfig(\haibao\classlibrary\jiepai\Config::LAST_SUPPORT_VERSION_420), $version)){
            $sql .= " AND t1.Type NOT IN (101,102,103,104,105,106,107,108) AND (SELECT count(*) as count from cms_article_content WHERE ArticleID=t1.TypeID AND Type=14) = 0 ";
        }*/
        $sql .= " ORDER BY t1.UpIndex,t1.CreateTime desc LIMIT 6;";

        $result = $this->query($sql);
        $list = array();
        while($row = $result->fetch_assoc()){
            array_push($list, $row);
        }

        return self::mergeDataAndImage($list, 'Picture');

    }

    public function getFindingsFashionistas(){
        //1082262
        $directoryPicture = $this->getDirectoryPicture();
        $leaderboardPicture = $this->GetRandomFashionistaInfo();

        return array($directoryPicture, $leaderboardPicture);
    }

    //获取发现->名录图片
    public function getDirectoryPicture(){
        $celebrityData = new \haibao\cms\data\Celebrity();
        $celebrityIds = $celebrityData->getCelebrityIdsFromApp();
        if($celebrityIds){
            $articleSql = "SELECT cac.ContentInfo from cms_articles ca " .
                "left join cms_article_celebrity cat on ca.ArticleID=cat.ArticleID " .
                "left join cms_article_content cac on cac.ArticleID=ca.ArticleID " .
                "WHERE ca.Flag=0 and ca.PublishStatus=1 AND ca.Type=2 AND cac.Flag=0 AND cac.Type=0 AND cat.CelebrityID=%s ORDER BY ca.PublishTime desc limit 1;";

            $info = $this->query($articleSql,$celebrityIds)->fetch_assoc();

            if($info){
                return self::mergeOneDataAndImage($info, (int)$info['ContentInfo']);
            }
        }


        return array();
    }
    //获取发现->排行榜图片
    public function getRandomFashionistaInfo(){
        $celebrityData = new \haibao\cms\data\Celebrity();
        $celebrityIds = $celebrityData->getCelebrityIdsFromApp('HotPoints','DESC',100);
        if($celebrityIds){
            $celebrityId = $celebrityIds[array_rand($celebrityIds)];
            $articleSql = "SELECT cac.ContentInfo from cms_articles ca " .
                "left join cms_article_celebrity cat on ca.ArticleID=cat.ArticleID " .
                "left join cms_article_content cac on cac.ArticleID=ca.ArticleID " .
                "WHERE ca.Flag=0 and ca.PublishStatus=1 AND ca.Type=2 AND cac.Flag=0 AND cac.Type=0 AND cat.CelebrityID=%s ORDER BY ca.PublishTime desc limit 1;";

            $info = $this->query($articleSql,array($celebrityId))->fetch_assoc();

            if($info){
                return self::mergeOneDataAndImage($info, (int)$info['ContentInfo']);
            }
        }
        return array();
    }

    public function getNineClockBooth($version){
        $articleData = new Article();
        $nine = $this->getNineClockBoothArticle();
        $isTodayHaveNew = $this->getIsTodayNewNine();
        $juryArticle = $articleData->getLastJuryArticle('findings');
        $weekReviews = $this->getWeekReviewsBoothArticle();
        return array($nine, $isTodayHaveNew, $juryArticle, $weekReviews);
    }

    /**
     * 查询最新一篇一周最点评文章
     */
    public function getWeekReviewsBoothArticle(){
        $sql = 'select a.ArticleID,a.Title,c.ContentInfo from cms_articles as a left join cms_article_tags as b on a.ArticleID=b.ArticleID left join cms_article_content as c on a.ArticleID=c.ArticleID where b.TagID = 90890 and PublishStatus=1 and a.Flag=0 and c.Type=6 order by a.PublishTime desc limit 1';
        $result = $this->query($sql, array($sql))->fetch_assoc();
        if($result){
            return self::mergeOneDataAndImage($result, (int)$result['ContentInfo']);
        }
        return array();
    }

    public function getNineClockBoothArticle(){
        $sql = "SELECT ca.ArticleID,cac.ContentInfo FROM cms_articles ca " .
            "LEFT JOIN cms_article_content cac on ca.ArticleID=cac.ArticleID " .
            "where ca.Type=107 " .
            "AND cac.Type=0 AND ca.Flag=0 AND cac.Flag=0 AND ca.PublishStatus=1 AND ca.PublishTime<NOW() ";

        if(time() <= strtotime(date('Y-m-d 21:00:00'))){
            $sql .= "AND ca.PublishTime < CURDATE() ";
        }
        $sql .=" ORDER BY ca.PublishTime DESC LIMIT 1;";
        $result = $this->query($sql, array($sql))->fetch_assoc();
        if($result){
            return self::mergeOneDataAndImage($result, (int)$result['ContentInfo']);
        }
        return array();
    }

    public function getIsTodayNewNine(){
        $sql="SELECT COUNT(*) as count from cms_articles WHERE Type=107 AND Flag=0 AND PublishStatus=1 AND NOW()>='".date('Y-m-d 21:00:00')."' AND DATE_FORMAT(PublishTime,'%Y-%m-%d')=CURDATE(); ";
        $result = $this->query($sql)->fetch_assoc();
        return $result['count']>0?1:0;
    }

    public function getSpecialColumnList($version, $isEditor){
        $typelist = array(101,102,103,104,105,106);
        $list = array();
        foreach($typelist as $type){
            $tempSql = '';
            $tempSql .= "SELECT cc.UpdateDate,cc.ColumnName,ca.PublishTime,ca.ArticleID,ca.Type,ca.Title,cac.ContentInfo " .
                "from cms_articles ca " .
                "LEFT JOIN cms_article_content cac on ca.ArticleID=cac.ArticleID " .
                "LEFT JOIN cms_columns cc on cc.TagID=".$type."" .
                " WHERE cac.Type=0 AND ca.Flag=0 AND ca.PublishStatus = 1 AND cac.Flag=0 AND cc.ColumnType=3 AND ca.Type =".$type;
            if(!$isEditor){
                $tempSql .= " AND ca.PublishTime < Now() ";
            }
            $tempSql .= " ORDER BY ca.PublishTime desc limit 1;";
            $result = $this->query($tempSql)->fetch_assoc();
            array_push($list, $result);
        }

        return self::mergeDataAndImage($list);
    }

    public function getFashionWallPapers(){
        $sql = "SELECT ca.ArticleID as BrandID,ct.TagName as BrandName,ca.SubtitleType as FileDescription from cms_articles ca " .
            "inner join cms_article_tags cat on cat.ArticleID=ca.ArticleID " .
            "inner join cms_tags ct on cat.TagID=ct.TagID AND ct.CategoryID=5 AND ct.Flag=0 WHERE ca.Type=" .\haibao\classlibrary\jiepai\Config::getConfig(\haibao\classlibrary\jiepai\Config::WALLPAPER_ARTICLE_TYPE).
            " AND ca.PublishStatus=1 AND ca.PublishTime < NOW() ORDER BY ca.PublishTime desc LIMIT 2";

        $results = array();
        $query = $this->query($sql);

        while ($fetchArr = $query->fetch_assoc()){

            $contentSql = "SELECT cac.ContentInfo,cac.ID as ContentID from cms_article_content cac  WHERE cac.Type=4 AND cac.Flag=0 " .
                "AND cac.ArticleID=%s ORDER BY ShowIndex ASC;";
            $result = $this->query($contentSql, array($fetchArr['BrandID']));
            $tempList = array();
            while($row = $result->fetch_assoc()){
                array_push($tempList, $row);
            }
            $tempList = self::mergeDataAndImage($tempList);

            $tempArr = array();
            foreach($tempList as $key=>&$temp){
                if(!$temp['Picture']){
                    unset($tempList[$key]);
                    continue;
                }
                $temp['FileID'] = $temp['ContentInfo'];
                $temp['Ratio'] = 1;
                $temp['FileDescription'] = $fetchArr['FileDescription'];
                unset($temp['ContentInfo']);
                array_push($tempArr, $temp);
            }
            array_push($results, array('BrandID'=>$fetchArr['BrandID'], 'BrandName'=>$fetchArr['BrandName'], 'list'=>$tempArr));
        }
        return $results;
    }

    public function getCoverInfo(){
        $sql = "SELECT t1.CoverID,t1.Title,t1.Layout,t1.Color,t1.Picture FROM `cms_covers` t1  WHERE t1.Flag = 0 ORDER BY t1.CoverID desc LIMIT 1; ";
        $result = $this->query($sql)->fetch_assoc();
        if($result){
            return self::mergeOneDataAndImage($result,$result['Picture']);
        }
    }

    public function getTagRelation($tagId){
        $sql = 'SELECT DISTINCT t.TagID,t.TagName as Name FROM cms_tags_relation r ' .
            'LEFT JOIN cms_tags t ON r.TagID2=t.TagID ' .
            'WHERE t.Flag = 0 AND r.TagID=%s';
        $result = $this->query($sql, array($tagId));

        $list = array();
        while($row = $result->fetch_assoc()){
            array_push($list, $row);
        }
        return $list;
    }
    public function getTagArticlesCount($tagId){
        $sql = "SELECT count(DISTINCT t1.ArticleID) as count from cms_article_tags t1 
                LEFT JOIN cms_articles t2 on t1.ArticleID = t2.ArticleID 
                where t2.Flag = 0 AND t2.PublishStatus = 1 AND t1.TagID = %s AND t1.Flag = 0";
        return $this->query($sql, array($tagId))->fetch_assoc();
    }


    public function getTagPicture($tagId){

        $sql = 'SELECT c.ContentInfo FROM cms_article_tags t ' .
        'LEFT JOIN cms_articles a ON t.ArticleID=a.ArticleID ' .
        'LEFT JOIN cms_article_content c ON t.ArticleID=c.ArticleID AND c.Type=0 ' .
        'WHERE t.Flag = 0 AND a.Flag = 0 AND c.Flag = 0 AND t.TagID=%s order by a.PublishTime desc limit 100';
        $result = $this->query($sql, array($tagId));
        $list = array();
        while($row = $result->fetch_assoc()){
            array_push($list, $row);
        }
        return self::mergeDataAndImage($list);
    }

    public function getTagsArticles($fashionistaId, $cursor){
        $sql = "SELECT DISTINCT t3.ArticleID,t3.Title,t3.Type,c.ContentInfo,t3.PublishTime from cms_article_celebrity t1 " .
            "LEFT JOIN cms_articles t3 on t1.ArticleID = t3.ArticleID " .
            "LEFT JOIN cms_article_content c ON t1.ArticleID=c.ArticleID AND c.Type=0 " .
            "WHERE t1.CelebrityID = %s " ;
        $sql .= " AND t3.Type in (1,2,101,102,103,104,105,106) ";
        $sql .= " AND t3.Flag = 0 AND t3.PublishStatus = 1 AND t3.PublishTime < NOW() ";
        if ($cursor) $sql .= ' AND t3.PublishTime < "' .date('Y-m-d H:i:s'). '"';
        $sql .= " ORDER BY t3.PublishTime DESC LIMIT " . (\haibao\classlibrary\jiepai\Config::getConfig(\haibao\classlibrary\jiepai\Config::LARGE_ARTICLE_PAGE_SIZE)+1);

        $result = $this->query($sql, array($fashionistaId));
        $list = array();
        while($row = $result->fetch_assoc()){
            array_push($list, $row);
        }
        return self::mergeDataAndImage($list);
    }

    public function getTagArticles($tagId, $cursor){
        $sql = 'SELECT Distinct t.ArticleID,a.Title,a.Type,c.ContentInfo,a.PublishTime FROM cms_article_tags t ' .
            'LEFT JOIN cms_articles a ON t.ArticleID=a.ArticleID ' .
            'LEFT JOIN cms_article_content c ON t.ArticleID=c.ArticleID AND c.Type=0 ' .
            'WHERE t.TagID=%s  ';
        $sql .= " AND a.Type in (1,2,101,102,103,104,105,106) ";
        $sql .= ' AND a.PublishTime < NOW() AND a.Flag=0 AND a.PublishStatus = 1 AND a.PublishTime < NOW() ';
        if ($cursor) $sql .= ' AND a.PublishTime < "' .date('Y-m-d H:i:s'). '"';

        $sql .= " ORDER BY a.PublishTime DESC LIMIT " . \haibao\classlibrary\jiepai\Config::getConfig(\haibao\classlibrary\jiepai\Config::LARGE_ARTICLE_PAGE_SIZE);
        $result = $this->query($sql, array($tagId));
        $list = array();
        while($row = $result->fetch_assoc()){
            array_push($list, $row);
        }
        return self::mergeDataAndImage($list);
    }

    public function getColumnById($columnId){

        $sql = 'SELECT c.ColumnID,c.ColumnName,c.Description,c.TagID,c.ColumnType,c.PictureID,c.Status as CanSubscribe  FROM cms_columns c ' .
            'LEFT JOIN cms_tags ct on c.TagID = ct.TagID '.
            'WHERE c.ColumnID=%s';
        $result = $this->query($sql, array($columnId))->fetch_assoc();
        if($result){
            return self::mergeOneDataAndImage($result, $result['PictureID']);
        }
        return array();

    }


    public function getColumnArticles($columnId, $cursor){

        $sql = 'SELECT a.ArticleID,a.PublishTime,a.Title,a.Type,a.PictureNum,c.ContentInfo FROM cms_articles a  ' .
            'LEFT JOIN cms_article_content c ON a.ArticleID=c.ArticleID  ' .
            'WHERE a.ColumnID=%s AND a.Flag=0  AND a.PublishTime < NOW() ';
        $sql .= " AND a.Type in (1,2) ";
        if($cursor){
            $sql .= " AND ca.PublishTime < '".date('Y-m-d H:i:s', $cursor)."' ";
        }
        $sql .= ' AND c.Type=0 ORDER BY a.PublishTime DESC LIMIT ' . (\haibao\classlibrary\jiepai\Config::getConfig(\haibao\classlibrary\jiepai\Config::LARGE_ARTICLE_PAGE_SIZE)+1);

        $result = $this->query($sql, array($columnId));
        $articleList = array();
        while($row = $result->fetch_assoc()){
            array_push($articleList, $row);
        }
        if($articleList){
            $articleList = self::mergeDataAndImage($articleList);
        }
        return $articleList;
    }

    public function getSecondColumns($columnId){
        $sql = "SELECT t1.ColumnID,t1.ColumnName as Name,t1.PictureID from cms_columns t1 WHERE t1.Flag = 0 AND t1.ColumnType = 1 AND t1.TopColumnID = %s ORDER BY ShowIndex ";

        $result = $this->query($sql, array($columnId));
        $list = array();
        while($row = $result->fetch_assoc()){
            array_push($list, $row);
        }
        if($list){
            $list = self::mergeDataAndImage($list, 'PictureID');
        }
        return $list;
    }

    public function getHotRecommendTopics(){

        $sql = 'SELECT t.TopicID,t.TopicTitlePictureID FROM cms_topics t ' .
            'WHERE t.Flag=0 ORDER BY t.TopicID DESC LIMIT ' . \haibao\classlibrary\jiepai\Config::getConfig(\haibao\classlibrary\jiepai\Config::TOPIC_LIST_SIZE);

        $result = $this->query($sql);
        $list = array();
        while($row = $result->fetch_assoc()){
            array_push($list, $row);
        }
        if($list){
            $list = self::mergeDataAndImage($list, 'TopicTitlePictureID');
        }
        return $list;
    }

    public function getTodayNineArticle(){

        $sql = "SELECT ca.ArticleID,ca.Type,ca.Title,ca.PublishTime,cac.ContentInfo FROM cms_articles ca " .
            "LEFT JOIN cms_article_content cac on ca.ArticleID=cac.ArticleID " .
            "WHERE ca.Flag = 0 AND cac.Flag=0 AND ca.Type = 107 AND cac.Type=14 AND ca.PublishStatus=1 AND ca.PublishTime<=NOW() ORDER BY ca.PublishTime DESC LIMIT 1;";

        $result = $this->query($sql, array($sql))->fetch_assoc();
        if($result){
            return self::mergeOneDataAndImage($result, (int)$result['ContentInfo']);
        }
        return array();
    }

    public function getColumnHots($columnId){

        $hotColumns = \haibao\jiepai\cache\Crontab::get(\haibao\classlibrary\jiepai\Config::getConfig(\haibao\classlibrary\jiepai\Config::COLUMN_HOTS_KEY).$columnId);
        return $hotColumns;
    }

    public function getColumnArticlesNew($columnInfo, $tagId, $cursor){

        $articleSql = "SELECT DISTINCT ca.ArticleID,ca.PublishTime,ca.Type,ca.Title,cac.ContentInfo from cms_articles ca " .
            "inner join cms_article_content cac on ca.ArticleID=cac.ArticleID and cac.Type=0 and cac.Flag = 0 and ca.Title not like %s";

        if($tagId){
            $articleSql .= " inner join cms_article_tags cat1 on cat1.ArticleID=ca.ArticleID and cat1.TagID=".$tagId;
        }

        if($columnInfo['ColumnType'] == 2){//标签栏目只有画报

            $tagIdConfig = \haibao\classlibrary\jiepai\Config::getConfig(\haibao\classlibrary\jiepai\Config::TAG_ID);
            $articleSql .= " left join cms_article_tags cat on ca.ArticleID=cat.ArticleID WHERE 1=1 AND ca.Type=2  ";
            if($columnInfo['TagID'] == $tagIdConfig['COLUMN_FASHION']){//如果是时尚圈街拍，全部中筛选素人标签
                if($tagId){
                    $articleSql .= " and (cat.TagID=".$columnInfo['TagID']." OR cat.TagID=".$tagIdConfig['NONAME'].") ";
                }else if($tagId == $tagIdConfig['NONAME']){
                    $articleSql .= " AND (cat.TagID=".$tagIdConfig['NONAME'].") ";
                }else{
                    $articleSql .= " and (cat.TagID=".$columnInfo['TagID']." OR cat.TagID=".$tagIdConfig['NONAME'].") ";
                }
            }else{
                $articleSql .= " and cat.TagID=".$columnInfo['TagID']." ";
            }

        }else {
            $articleSql .= " WHERE ca.ColumnID=".$columnInfo['ColumnID'];
        }

        if ($cursor) $articleSql .= ' and ca.PublishTime < "' .date('Y-m-d H:i:s', $cursor). '"';
        $articleSql .= " AND ca.Type in (1,2,101,102,103,104,105,106) and ca.Flag = 0 AND ca.PublishStatus = 1 AND ca.PublishTime < NOW() AND ca.PublishTime > '".date('Y-m-d H:i:s', strtotime('-400 days'))."' ";

        if($tagId){//60天之前的文章根据积分排序，之后的根据时间倒序
            $articleSql .=" ORDER BY IF((ca.PublishTime > '".date('Y-m-d H:i:s', strtotime('-60 days'))."'),ca.Scores,ca.PublishTime) desc ";
        }else{
            $articleSql .= " ORDER BY ca.PublishTime desc ";
        }
        $articleSql .= " LIMIT " . (\haibao\classlibrary\jiepai\Config::getConfig(\haibao\classlibrary\jiepai\Config::LARGE_ARTICLE_PAGE_SIZE)+1);

        $result = $this->normalQuery($articleSql, array('%一周最点评%'));
        if($result){
            return self::mergeDataAndImage($result);
        }
        return $result;

    }

    public function getColumnTags($columnId){
        $sql = "SELECT ID as TagID,Text as Name FROM cms_columns_tags WHERE ColumnID=%s ORDER BY ShowIndex ASC;";
        return $this->normalQuery($sql, array($columnId));

    }

    public function getHotestColumnArticle($columnId){
        // $startDate=date('Y-m-d', strtotime("-30 days"));
        // $sql = "SELECT ArticleID,Title,Type From cms_articles WHERE (PublishTime<=NOW() AND PublishTime>=%s) AND Flag=0 AND PublishStatus=1 AND ColumnID=%s AND Type in (1,2) AND Title not like %s ORDER BY Scores DESC LIMIT 1;";
        // return $this->query($sql, array($startDate, $columnId, '%一周最点评%'))->fetch_assoc();
        $startDate = date('Y-m-d', strtotime("-14 days"));
        $sql = "SELECT ArticleID,Title,Type From cms_articles WHERE (PublishTime<=NOW() AND PublishTime>=%s) AND Flag=0 AND PublishStatus=1 AND ColumnID=%s AND Type in (1,2) AND Title not like %s ORDER BY Scores DESC LIMIT 1";

        $retArr = $this->query($sql, array($startDate, $columnId, '%一周最点评%'))->fetch_assoc();
        if(!$retArr){
            $sql = "SELECT ArticleID,Title,Type From cms_articles WHERE PublishTime<=NOW() AND Flag=0 AND PublishStatus=1 AND ColumnID=%s AND Type in (1,2) AND Title not like %s ORDER BY PublishTime DESC LIMIT 1";
            return $this->query($sql, array($columnId, '%一周最点评%'))->fetch_assoc();
        }
    }

    public function getWeekReviewsArticles($nextCursor = null){
        $sql = 'select a.ArticleID,a.Title,c.ContentInfo,a.PublishTime,a.Type from cms_articles as a';
        $sql .= ' left join cms_article_tags as b on a.ArticleID=b.ArticleID ';
        $sql .= ' left join cms_article_content as c on a.ArticleID=c.ArticleID ';
        $sql .= ' where ';
        if($nextCursor){
            $sql .= ' PublishTime<"'.$nextCursor.'" and ';
        }
        $sql .= ' b.TagID = 90890 and PublishStatus=1 and a.Flag=0 and c.Type=0 order by a.PublishTime desc limit 30';
        $result = $this->query($sql);
        $reviewArr = array();
        while($row = $result->fetch_assoc()){
            array_push($reviewArr, $row);
        }
        if($reviewArr){
            $reviewArr = $this->mergeDataAndImage($reviewArr);
        }
        return $reviewArr;
    }

    public function getColumnTagArticles($hotestArticles, $hotTags, $columnId){

        $columnTags = array_slice($hotTags,0,3);

        $articles = $articleIds = array();

        array_push($articleIds,$hotestArticles['ArticleID']);
        for($i = 0; $i < count($columnTags);$i++){

            $articleInfo = $this->getColumnTagArticle($articleIds, (int)$columnId,$columnTags[$i]);
            if($articleInfo){
                array_push($articleIds, $articleInfo['ArticleID']);
                array_push($articles, $articleInfo) ;
            }
        }
        return $articles;
    }

    public function getColumnTagArticle($articleId, $columnId,$tagInfo)
    {

        $sql = "SELECT ca.ArticleID,ca.Title,ca.Type FROM cms_articles ca " .
            "INNER JOIN cms_article_tags cat ON ca.ArticleID=cat.ArticleID WHERE ca.PublishStatus=1 AND ca.PublishTime<=NOW() AND ca.Flag=0 AND ca.PublishTime>='" .
            date('Y-m-d H:i:s', strtotime("-60 days")) . "' AND ca.ColumnID=%s";

        if (is_array($articleId)) {
            $sql .= " AND ca.ArticleID not in (" . implode(',', $articleId) . ") ";
        } else {
            $sql .= " AND ca.ArticleID <> " . $articleId . "";
        }
        $sql .= " AND cat.TagID=%s ORDER BY Scores DESC LIMIT 1";

        $result = $this->query($sql, array($columnId, $tagInfo['TagID']))->fetch_assoc();

        if($result){
            $data = new Article();
            $articleInfo = $data->getArticleInfoById($result['ArticleID']);
            $temp = array(
                'ArticleID'=>$result['ArticleID'],
                'TagID'=>$tagInfo['TagID'],
                'KeyWord'=>(isset($tagInfo['TagName']))?$tagInfo['TagName']:$tagInfo['Name'],
                'Title'=>$result['Title'],
                'Type'=>$result['Type'],
                'Ratio'=>2
            );
            return array_merge($articleInfo, $temp);
        }
        return array();
    }

    public function getColumnTagList($tagId){
        $sql = "SELECT TagID FROM cms_columns_tags WHERE ID=%s";
        $result = $this->query($sql, array($tagId));
        $list = array();
        while($result->fetch_assoc()){

            array_push($list,$result->getData('TagID'));
        }
        return $list;
    }

    public function getPopularTags(){
        $notUsedTagId = array(45437,89216,45510,45491);
        $sql = "SELECT DISTINCT(TypeID) from cms_blocklist WHERE Type = 2 AND Flag = 0;";

        $result = $this->query($sql);
        $typeIds = array();
        while($result->fetch_assoc()){
            array_push($notUsedTagId, $result->getData('TypeID'));
        }

        $startDate = date('Y-m-d',strtotime("-50 days"));
        $sql = "SELECT t2.TagID ,t3.TagName as 'Name' ,COUNT(*) as 'count' FROM cms_articles t1 " .
            "LEFT JOIN cms_article_tags t2 on t1.ArticleID = t2.ArticleID " .
            "LEFT JOIN cms_tags t3 on t2.TagID = t3.TagID " .
            " WHERE t1.Type in (1,2,101,102,103,104,105,106) AND t3.CategoryID != 2 AND t1.Flag = 0 AND t2.Flag = 0 AND t3.Flag = 0 AND t3.CategoryID NOT IN (11,14,9,10,15)" .
            " AND t2.TagID NOT IN (" . implode(',', $notUsedTagId) . ") " .
            " AND t1.PublishTime >'" .$startDate .
            "' AND t1.PublishStatus = 1 AND t2.TagID GROUP BY t3.TagID ORDER BY count desc LIMIT 100;";


        $list = array();
        $result = $this->query($sql);
        while($row = $result->fetch_assoc()){
            array_push($list, $row);
        }
        return $list;
    }

    public function getTagPictureForLatelyPopular($tagId, $fileIdList = array()){

        $sql = "SELECT t1.Picture from cms_tags t1 WHERE t1.TagID=" . $tagId . " limit 1";
        $result = $this->query($sql)->fetch_assoc();
        if ($result['Picture']) {
            array_push($fileIdList, $result['Picture']);
            return $result;
        } else {
            $sql = "SELECT t1.ArticleID,t3.ContentInfo FROM cms_article_tags t1" .
                " LEFT JOIN cms_articles t2 on t1.ArticleID = t2.ArticleID " .
                " LEFT JOIN cms_article_content t3 on t1.ArticleID = t3.ArticleID AND t3.Type = 0 " .
                " WHERE t2.Type in (1,2,101,102,103,104,105,106) AND t1.TagID = " . $tagId;
            if ($fileIdList) $sql .= " AND t3.ContentInfo NOT IN (" . implode(',', $this->fileIdList) . ") ";
            $sql .= " ORDER BY t2.Scores DESC LIMIT 10; ";

            $list = array();
            $result = $this->query($sql);

            while($row = $result->fetch_assoc()){
                array_push($list, $row);
            }
            if($list){
                $list = $this->mergeDataAndImage($list);
            }
            return array($list[array_rand($list, 1)],$fileIdList);
        }
        return array(array(), $fileIdList);
    }
}
